<?php

class Boot{
    
    /**
     * SAPI模式:CLI,CGI,apache_mod
     * @var boolean
     */
    public static $isCli = FALSE;
    
    private function __construct() {
        
    }
    
    public static function getInstance(){
        static $instance = NULL;
        if ($instance === NULL || !is_object($instance)){
            $instance = new Boot();
        }
        return $instance;
    }
    
    public function start(){
        
        // 判断是cli还是other sapi
        if(PHP_SAPI === 'cli'){
            Boot::$isCli = true;
        }
        else{
            Boot::$isCli = false;
        }
        
        try{
            $stream = $this->getContent(Boot::$isCli);
            $interpreter = new Interpreter($stream);
            $interpreter->run();
            exit(0);
        }
        catch(Exception $e){
            
            $ret = $e->getFile()."\t".$e->getLine()."\t".$e->getCode()."\t".$e->getMessage()."\n";
            echo $ret;
            exit(1);
        }
    }
    
    /**
     * 读取js代码，并且放入一个字符串
     * @param boolean $isCli
     * @return string $stream
     */
    public function getContent($isCli){
        // 从Command Line中获取文件
        if($isCli){
            if(!empty($argv[1])){
                $file = trim($argv[1]);
            }else{
                $file = CLI_DEFAULT_FILE;
            }
            
            $fr = new FileReader();
            $stream = $fr->read($file);
        }
        
        // 从HTTP POST请求中获取文件
        else{
            $hr = new HttpReader();
            $stream = $hr->read();
        }
        return $stream;
    }
}